import axios from 'axios';
import { getToken } from '@/utils/token';
import { useUserStore } from '@/stores/userStore';

const baseURL = import.meta.env.VITE_PROXY_PREFIX || '/api';

const axiosInstance = axios.create({
    baseURL,
    timeout: 5000
});

// 请求拦截器：自动添加Token
axiosInstance.interceptors.request.use(
    (config) => {
        const token = getToken();
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => Promise.reject(error)
);

// 响应拦截器：处理Token过期
axiosInstance.interceptors.response.use(
    (response) => response.data,
    (error) => {
        if (error.response?.status === 401) {
            const userStore = useUserStore();
            userStore.logout(); // Token过期，自动登出
            window.location.href = '/login';
        }
        return Promise.reject(error);
    }
);

export default axiosInstance;
